<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>  
<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<html>
<head>
<title>店铺分类管理</title>
<script src="${ctx}/static/js/base.js" type="text/javascript"></script>
<script>
  var memberUserId = ${shop.memberUser.id};
  var shopId = ${shop.id};
  // Sample data:
  // [
  //   {'id': 101, 'level': 1, 'name': '衣服', 'order': 1000, 'sub': [
  //        {'id': 10101, 'level': 2, 'name': '上衣', 'order': 1000, 'sub': [
  //                {'id': 1010101, 'level': 3, 'name': 'XX上衣', 'order': 1000},
  //                {'id': 1010102, 'level': 3, 'name': 'XX上衣', 'order': 2000},
  //                {'id': 1010103, 'level': 3, 'name': 'XX上衣', 'order': 3000},
  //            ]},
  //        {'id': 10102, 'level': 2, 'name': '裤子', 'order': 2000, 'sub': [
  //                {'id': 1010201, 'level': 3, 'name': 'XX裤子', 'order': 1000},
  //                {'id': 1010202, 'level': 3, 'name': 'XX裤子', 'order': 2000},
  //                {'id': 1010203, 'level': 3, 'name': 'XX裤子', 'order': 3000},
  //            ]},
  //        {'id': 10103, 'level': 2, 'name': '包包', 'order': 3000, 'sub': [
  //                {'id': 1010301, 'level': 3, 'name': 'XX包', 'order': 1000},
  //                {'id': 1010302, 'level': 3, 'name': 'XX包', 'order': 2000},
  //                {'id': 1010303, 'level': 3, 'name': 'XX包', 'order': 3000},
  //            ]},
  //      ]},
  //   {'id': 102, 'level': 1, 'name': '配饰', 'order': 2000, 'sub': [
  //        ......
  //      ]},
  // ]
  var categoryList = [];
  $(document).ready(function() {
    getAndRenderCategoryList();
    $('#add').click(function() {
      showEditArea('add');
    });
    $('.update').live('click', function() {
      var nameAndOrder = getNameAndOrder($(this).attr('cid'));
      showEditArea('modify', $(this).attr('level'), $(this).attr('cid'), nameAndOrder[0], nameAndOrder[1]);
    });
    $('.delete').live('click', function() {
      Momo.ajax('删除', '${ctx}/member/shop/ajax-category-delete', {cid: $(this).attr('cid')}, refreshUI);
    });
    $('#edit_l1ids').change(function() {
      var l1Id = $(this).val();
      var data = [];
      for (var i = 0; i < categoryList.length; i++) {
        if (l1Id == categoryList[i]['id']) {
          data = categoryList[i]['sub'];
          break;
        }
      }
      renderSelect($('#edit_l2ids'), data);
    });
    $('#edit').submit(function(e) {
      e.preventDefault();
      var action = $('#edit_action').val();
      if (action != 'add' && action != 'modify') {
        alert('ERROR: edit_action must be add or update');
        return;
      }
      var data = {
        name: $('#edit_name').val(),
        order: $('#edit_order').val(),
      };
      if (action == 'add') {
        if ($('#edit_l2ids').val() != 0) {
          data['l2id'] = $('#edit_l2ids').val();
          data['l1id'] = $('#edit_l1ids').val();
          data['level'] = 3;
        } else if ($('#edit_l1ids').val() != 0) {
          data['l1id'] = $('#edit_l1ids').val();
          data['level'] = 2;
        } else {
          data['level'] = 1;
        }
        Momo.ajax('新增', '${ctx}/member/shop/ajax-category-add', data, refreshUI);
      } else {  // action == 'modify'
        data['cid'] = $('#edit_cid').val(),
        Momo.ajax('更新', '${ctx}/member/shop/ajax-category-modify', data, refreshUI);
      }
    });
  });
  function refreshUI() {
    $('#edit').hide();
    getAndRenderCategoryList();
  }
  function getAndRenderCategoryList() {
    Momo.ajax('查询', '${ctx}/member/shop/ajax-category-get-all', {},
      function(resp) {
        categoryList = resp.cids;
        refreshCategoryList();
      });
  }
  function refreshCategoryList() {
    var list = $('#list').empty();
    $.each(categoryList, function(index, category) {
      refreshCategoryList2(category, 1);
    });
  }
  function refreshCategoryList2(category, level) {
    renderOneCategory(category, level);
    if (category['sub']) {
      $.each(category['sub'], function(index, c) {
        refreshCategoryList2(c, level + 1);
      });
    }
  }
  function renderOneCategory(category, level) {
    var row = $('#list_template').clone().attr('id', 'd_' + category['id']);
    row.attr('cid', category['id']).attr('level', category['level']);
    row.find('.l' + level).html(category['name']);
    row.find('.order').html(category['order']);
    row.find('.update').attr('cid', category['id']).attr('level', category['level']);
    row.find('.delete').attr('cid', category['id']).attr('level', category['level']);
    row.appendTo(list);
  }
  function renderSelect(select, data) {
    select.empty();
    data = data || [];
    select.append($('<option>').val(0).text('--------请选择分类--------'));
    for (var i = 0; i < data.length; i++) {
      select.append($('<option>').val(data[i]['id']).text(data[i]['name']));
    }
  }
  function getNameAndOrder(cid) {
    var d = $('#d_' + cid);
    var name = d.find('.l' + d.attr('level')).html();
    var order = d.find('.order').html();
    return [name, order];
  }
  function showEditArea(action, level, cid, name, order) {
    $('#edit_action').val(action);
    $('#edit_level').val(level || "");
    $('#edit_cid').val(cid || "");
    $('#edit_name').val(name || "");
    $('#edit_order').val(order || "");
    if (action == 'add') {
      $('#edit_category_path').show();
      $('#edit_category_path_for_update').hide();
      renderSelect($('#edit_l1ids'), categoryList);
      renderSelect($('#edit_l2ids'), []);
    } else {
      $('#edit_category_path').hide();
      $('#edit_category_path_for_update').show();
      $('#edit_category_path_for_update label').html(getCategoryPathString(cid, level));
      //$('#category_path_label').html('所属分类：' + getCategoryPathString(cid, level));
    }
    $('#edit').show();
  }
  function getCategoryPathString(cid, level) {
    for (var i = 0; level >= 1 && i < categoryList.length; i++) {
      if (level == 1 && categoryList[i]['id'] == cid) {
        return "无";
      }
      var l1 = categoryList[i];
      var l1sub = l1['sub'];
      for (var j = 0; level >= 2 && l1sub && j < l1sub.length; j++) {
        if (level == 2 && l1sub[j]['id'] == cid) {
          return l1['id'];
        }
        var l2 = l1sub[j];
        var l2sub = l2['sub'];
        for (var k = 0; level >= 3 && l2sub && k < l2sub.length; k++) {
          if (level == 3 && l2sub[k]['id'] == cid) {
            return l1['id'] + ' > ' + l2['id'];
          }
        }
      }
    }
  }
</script>
</head>
<body>
  <c:if test="${not empty message}">
    <div id="message" class="alert alert-success"><button data-dismiss="alert" class="close">×</button>${message}</div>
  </c:if>

  <form id="edit" action="" method="post" class="form-horizontal hide">
    <fieldset>
      <legend><small>新增/修改分类</small></legend>
      <input id="edit_action" type="hidden"/>
      <input id="edit_cid" type="hidden"/>
      <input id="edit_level" type="hidden"/>
      <div class="control-group">
        <label id="category_path_label" for="category_path" class="control-label">所属分类：</label>
        <div id="edit_category_path_for_update" class="controls">
          <label class="span3" id=""></label>
        </div>
        <div id="edit_category_path" class="controls">
          <div class="span3"><select id="edit_l1ids"></select></div>
          <div class="span3"><select id="edit_l2ids"></select></div>
        </div>
      </div>
      <div class="control-group">
          <label for="name" class="control-label">名称:</label>
          <div class="controls">
              <input type="text" id="edit_name" class="input-large required"/>
          </div>
      </div>
      <div class="control-group">
          <label for="name" class="control-label">排序:</label>
          <div class="controls">
              <input type="text" id="edit_order" class="input-large required"/>
          </div>
      </div>
      <div class="form-actions">
          <input id="edit_ok" class="btn btn-primary" type="submit" value="确定"/>&nbsp; 
          <input id="edit_cancel" class="btn" type="button" value="取消" onclick="$('#edit').hide();"/>
      </div>
    </fieldset>
  </form>
  <div class="row">
    <fieldset>
      <legend><small>分类列表</small></legend>
    </fieldset>
  </div>
  <table class="hide">
    <tr id="list_template">
      <td class="l1"></td>
      <td class="l2"></td>
      <td class="l3"></td>
      <td class="order"></td>
      <td>
        <input class="btn update" type="button" value="修改"/>
        <input class="btn delete" type="button" value="删除"/>
      </td>
    </tr>
  </table>
  <table id="contentTable" class="table table-striped table-bordered table-condensed">
    <thead><tr><th width="25%">一级</th><th width="25%">二级</th><th width="25%">三级</th><th width="5%">排序</th><th width="20%">管理</th></tr></thead>
    <tbody id="list">
    </tbody>
  </table>
  <div id="button" class="row">
    <input id="add" class="btn" type="button" value="新增"/>
  </div>
</body>
</html>
